package com.dhcc.emergency4mayor;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import com.dhcc.service.RoadNetWebService;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.Toast;

public class RainBowActivity extends Activity {
	private static final String TAG = "RainBowActivity";
	boolean clearThread = false;

	private Timer timer1 = new Timer();
	private Timer timer = new Timer();
	private TimerTask task, task1;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rainbowlayout);
		new Thread() {
			public void run() {

				if (isConnByHttp()) {

					task = new TimerTask() {
						@Override
						public void run() {
							RainbowReportString = RoadNetWebService
									.getRainBowReportString(
											"getTrafficIndexDetail",
											"", "全路网");

							Message message = new Message();
							message.what = 0;
							handler.sendMessage(message);
						}
					};

					timer.schedule(task, 500, 300000);

					task1 = new TimerTask() {
						@Override
						public void run() {

							/*
							 * FlyString = RoadNetWebService
							 * .getFlyTextMoreString("getRealAirportInfoInit");
							 */
							RoadReportString = RoadNetWebService.getTrafficAreaIndexReport("getCityAreaTrafficIndex");
							//System.out.println("roadString"+RoadReportString);
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
						}
					};

					timer1.schedule(task1, 500, 300000);

				} else {
					
					Message message = new Message();
					message.what = 2;
					handler.sendMessage(message);
				}

			}

		}.start();

		/*
		 * if(isConnByHttp()){ clearThread=true; handler = new Handler();
		 * handler.post(ReportLinesUI); handler.post(histogrmUI);
		 * 
		 * }else{
		 * 
		 * AlertDialog.Builder builder = new AlertDialog.Builder(this);
		 * builder.setTitle("错误"); builder.setMessage("无法连接服务器，请稍候重试");
		 * builder.setCancelable(false); // 禁止取消键
		 * builder.setNegativeButton("确认", new DialogInterface.OnClickListener()
		 * { public void onClick(DialogInterface dialog, int which) { finish();
		 * } }); builder.create().show();
		 * 
		 * }
		 */

	}

	private Handler handler = new Handler() {
		@Override
		// 当有消息发送出来的时候就执行Handler的这个方法
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			// 处理UI
			switch (msg.what) {
			case 0:
				handler.post(ReportLinesUI);

				break;
			case 1:
				handler.post(histogrmUI);
				break;
			case 2:
				CannotConnectServ();
				break;
			}

		}

	};
	AlertDialog.Builder builder;
	public void CannotConnectServ() {

		 builder = new AlertDialog.Builder(
				RainBowActivity.this);
		builder.setTitle("错误");
		builder.setMessage("无法连接服务器，请稍候重试");
		builder.setCancelable(false); // 禁止取消键
		builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		});
		builder.create().show();
	}

	public boolean isConnByHttp() {
		boolean isConn = false;
		URL url;
		HttpURLConnection conn = null;
		try {
			//交通委网
        	//url=new URL("http://172.24.186.187:8887/phone/webService");
			// 外网
			 //url = new URL("http://114.251.193.190:8899/phone");
			// 内网
				//url = new URL("http://172.18.18.203");
				 url = new URL("http://172.28.18.2:7777/phone/");
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(1000 * 6);
			if (conn.getResponseCode() == 200) {
				isConn = true;
			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			conn.disconnect();
		}
		return isConn;
	}
	protected void onPause() {
		super.onPause();
		if(builder!=null){
			
			builder.show().dismiss();
		}
		
	
		Log.e(TAG, "start onPause~~~");
		
		
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		timer1.cancel();
		timer.cancel();
		finish();
		Log.e(TAG, "start onDestroy~~~");
	}

	public void CannotConnect() {// 当服务器连接不上的时候 就提示用户 并关闭主程序。

		AlertDialog.Builder builder = new AlertDialog.Builder(
				RainBowActivity.this);
		builder.setTitle("错误");
		builder.setMessage("无法连接互联网，请稍候重试");
		builder.setCancelable(false); // 禁止取消键
		builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		});
		builder.create().show();

	}

	// 构建Runnable对象，在runnable中更新界面
	Runnable ReportLinesUI = new Runnable() {
		@Override
		public void run() {
		
			
				initLines();
			

		}

	};
	Runnable histogrmUI = new Runnable() {
		@Override
		public void run() {
		
			initHistogram();
			
		}

	};

	String RainbowReportString = null;
	List<String> xAxesString = new ArrayList<String>();

	protected void initLines() {
		//System.out.println("---------彩虹图信息-------------");
		//System.out.println(	RainbowReportString);
	
		if (RainbowReportString == null) {// 如果网络不通顺 则提示无法获取航班报表信息

			Toast toast = Toast.makeText(getApplicationContext(),
					"由于网络问题，无法获取彩虹图信息!", Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();

		} else if(RainbowReportString.length()==0||RainbowReportString.length()==1){//很可能没值或者只传了一个“#”井号
			
			
			 LinearLayout rainbowLayout = (LinearLayout)findViewById(R.id.rainbow);
			 rainbowLayout.setVisibility(8);
			 //有三个参数：Parameters:visibility One of VISIBLE, INVISIBLE, or GONE，想对应的三个常量值：0、4、8
			// VISIBLE:0  意思是可见的
			// INVISIBILITY:4 意思是不可见的，但还占着原来的空间
			// GONE:8  意思是不可见的，不占用原来的布局空间
			
			
			Toast toast = Toast.makeText(getApplicationContext(),
					"无彩虹图数据信息", Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		}
		else {

			// 每条曲线的名称
			String[] titles;
			String[] PartValue = RainbowReportString.split("#");
			String todayValue;
			String lastweekValue="";
			if(PartValue.length==2){
			     titles = new String[] { "上周同期", "当日" };
				 todayValue = PartValue[0];
				 lastweekValue = PartValue[1];
			}else{
				  titles = new String[] { "当日"};
				 todayValue = PartValue[0];
				
			}
			
			
			String[] TValue = todayValue.split(";");
			

			List<double[]> x = new ArrayList<double[]>(); // 点集的x坐标
			List<double[]> y = new ArrayList<double[]>(); // 点集的y坐标

			double[] inPortValueX = new double[TValue.length];
		
			double[] inPortValueY = new double[TValue.length];
			
			if(lastweekValue.length()!=0){
				
				String[] LValue = lastweekValue.split(";");
				double[] outPortValueX = new double[LValue.length];
				double[] outPortValueY = new double[LValue.length];
				
				for (int i = 0; i < LValue.length; i++) {
					String[] perValue = LValue[i].split(",");

					outPortValueX[i] = i;

					//xAxesString.add(perValue[0].toString());
					outPortValueY[i] = new Double(perValue[1].toString());

				}
				
				x.add(outPortValueX);
				y.add(outPortValueY);
			}
			
			xAxesString.clear();//清空数据
			for (int i = 0; i < TValue.length; i++) {
				String[] perValue = TValue[i].split(",");
				inPortValueX[i] = i;

				xAxesString.add(perValue[0].toString());
				inPortValueY[i] = new Double(perValue[1].toString());

			}

			
			x.add(inPortValueX);
			
			y.add(inPortValueY);
			

			// 保存点集数据 ，包括每条曲线的X，Y坐标
			XYMultipleSeriesDataset dataset = buildDatset(titles, x, y);
			
			int[] colors;
			PointStyle[] styles;
			if(lastweekValue.length()!=0){
				 colors = new int[] { Color.parseColor("#080808"),
						Color.parseColor("#0000FF") };// 每条曲线的颜色
				// 每条曲线点的形状
				 styles = new PointStyle[] { PointStyle.SQUARE,
						PointStyle.SQUARE };
				
			}else{
				
				 colors = new int[] { Color.parseColor("#080808")
							};// 每条曲线的颜色
					// 每条曲线点的形状
					 styles = new PointStyle[] { PointStyle.SQUARE};
				
			}
			
			// 曲线图的格式，包括颜色，值的范围，点和线的形状等等
			XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles,
					true);

			setChartSettings(renderer, "路网分时段交通指数", "", "交通指数", -1, 96, 0, 10,
					Color.BLACK, Color.BLACK);
			View chart = ChartFactory.getTimeChartView(this, dataset, renderer,
					"HH:mm");

			// setContentView(chart);
			// setContentView(R.layout.main);
			LinearLayout layout = (LinearLayout) findViewById(R.id.rainbow);
			layout.removeAllViews(); // 先remove再add可以实现统计图更新
			layout.addView(chart, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
		}

	}

	protected void setChartSettings(XYMultipleSeriesRenderer renderer,
			String title, String xTitle, String yTitle, double xMin,
			double xMax, double yMin, double yMax, int axesColor,
			int labelsColor) {
		//renderer.setLegendHeight(-2);
		renderer.setLegendTextSize(20);
		renderer.setAxisTitleTextSize(20);
		renderer.setChartTitle(title);
		renderer.setChartTitleTextSize(20);
		renderer.setXTitle(xTitle);
		renderer.setYTitle(yTitle);
		renderer.setXAxisMin(xMin);
		renderer.setMarginsColor(Color.parseColor("#a6d8ff"));
		renderer.setDisplayValues(true);
		renderer.setScale(0.9f);

		renderer.setXAxisMax(xMax);
		renderer.setYAxisMin(yMin);
		renderer.setYAxisMax(yMax);

		renderer.setPanEnabled(false, false);// 设置Y轴不可拖动 X轴可以拖动
		renderer.setPanLimits(new double[] { 0, 50, 0, 1000 });// 设置拖动范围
																// X最小为0最大为50Y最小为0最大为1000
		renderer.setShowGrid(true);// 显示网格线
		renderer.setGridColor(Color.BLACK);

		renderer.setApplyBackgroundColor(true);
		renderer.setBackgroundColor(Color.GRAY);
		renderer.setXLabelsAngle(-15); // 设置 X 轴标签倾斜角度 (clockwise degree)
		renderer.setDisplayChartValues(true);// 显示折线点上的数据
		renderer.setXLabels(0); // 设置X轴不显示数字（改用我们手动添加的文字标签）
		renderer.setAxesColor(axesColor);// 设置轴的颜色
		renderer.setXLabelsColor(labelsColor);// 设置X轴的字体颜色
		renderer.setYLabelsColor(0, Color.BLACK);// 设置Y轴的字体颜色
		renderer.setLabelsColor(labelsColor);
		renderer.setZoomEnabled(false, false);// 设置X轴可以缩放 Y轴不允许缩放
		renderer.setLabelsTextSize(20);
		/*
		 * for(int i=0;i<xAxesString.size();i++){
		 * 
		 * 
		 * 
		 * 
		 * }
		 */
		for (int i = 0; i < xAxesString.size(); i++) {
			if (i % 4 == 0) {// 四条数据显示一个X坐标的坐标标识
				renderer.addTextLabel(i, xAxesString.get(i));

			}

		}
	}

	private XYMultipleSeriesRenderer buildRenderer(int[] colors,
			PointStyle[] styles, boolean fill) {
		// 曲线图的格式，包括颜色，值的范围，点和线的形状等等
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		int length = colors.length;
		for (int i = 0; i < length; i++) {
			XYSeriesRenderer r = new XYSeriesRenderer();
			r.setColor(colors[i]);
			r.setChartValuesTextSize(18);
			r.setChartValuesTextAlign(Align.CENTER);
			r.setPointStyle(styles[i]);
			r.setFillPoints(fill);
			renderer.addSeriesRenderer(r);
		}

		return renderer;
	}

	private XYMultipleSeriesDataset buildDatset(String[] titles, List xValues,
			List yValues) {
		// 用于数据的存放
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();

		int length = titles.length; // 有几条线
		for (int i = 0; i < length; i++) {
			// XYseries对象,用于提供绘制的点集合的数据
			XYSeries series = new XYSeries(titles[i]); // 根据每条线的名称创建
			double[] xV = (double[]) xValues.get(i); // 获取第i条线的数据
			double[] yV = (double[]) yValues.get(i);
			int seriesLength = xV.length; // 有几个点

			for (int k = 0; k < seriesLength; k++) // 每条线里有几个点
			{
				series.add(xV[k], yV[k]);
			}

			dataset.addSeries(series);
		}

		return dataset;
	}

	String RoadReportString;
	List<String> xAxesString2 = new ArrayList<String>();

	protected void initHistogram() {
		//System.out.println("---------柱状图信息-------------");
		
		if (RoadReportString == null) {// 如果网络不通顺 则提示无法获取航班报表信息

			Toast toast = Toast.makeText(getApplicationContext(),
					"由于网络问题，无法获取路网报表信息!", Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();

		} else if(RoadReportString.length()==0||RoadReportString.length()==1){//很可能没值或者只传了一个“#”井号
			
			LinearLayout histogramLayout = (LinearLayout)findViewById(R.id.histogram);
			histogramLayout.setVisibility(8);
			Toast toast = Toast.makeText(getApplicationContext(),
					"无柱状图数据信息", Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		}else {

			// 每条曲线的名称
			
			String[] PartValue = RoadReportString.split("#");
			String todayValue;
			String lastweekValue="";
			if(PartValue.length==2){
				
				 todayValue = PartValue[0];
				 lastweekValue = PartValue[1];
			}else{
				
				 todayValue = PartValue[0];
				
			}
			
			String[] TValue = todayValue.split(";");
			
		
			List<double[]> x = new ArrayList<double[]>(); // 点集的x坐标
			List<double[]> y = new ArrayList<double[]>(); // 点集的y坐标
			
			double[] inPortValueX = new double[TValue.length];
			
			double[] inPortValueY = new double[TValue.length];
			
			String[] titles;
			if(lastweekValue.length()!=0){
				titles = new String[] { "上周同期", "当日" };
				String[] LValue = lastweekValue.split(";");
				double[] outPortValueX = new double[LValue.length];
				double[] outPortValueY = new double[LValue.length];
				
				for (int i = 0; i < LValue.length; i++) {
					String[] perValue = LValue[i].split(",");

					outPortValueX[i] = i;

					//xAxesString2.add(perValue[0].toString());
					outPortValueY[i] = new Double(perValue[1].toString());
					
				}
				x.add(outPortValueX);
				y.add(outPortValueY);
			}else{
				
				
				titles = new String[] { "当日"};
			}
			
			xAxesString2.clear();//清空数据
			for (int i = 0; i < TValue.length; i++) {
				String[] perValue = TValue[i].split(",");
				inPortValueX[i] = i;

				xAxesString2.add(perValue[0].toString());
				inPortValueY[i] = new Double(perValue[1].toString());

			}

		
			x.add(inPortValueX);
		
			y.add(inPortValueY);
			
			/*double[] inPortValueX = new double[SingleValue.length];

			double[] inPortValueY = new double[SingleValue.length];
			xAxesString2.clear();//清空数据
			for (int i = 0; i < SingleValue.length; i++) {
				String[] perValue = SingleValue[i].split(",");

				inPortValueX[i] = i;
				
				xAxesString2.add(perValue[0].toString());
				inPortValueY[i] = new Double(perValue[1].toString());

			}
			x.add(inPortValueX);

			y.add(inPortValueY);
*/
			// 保存点集数据 ，包括每条曲线的X，Y坐标
			XYMultipleSeriesDataset dataset = buildDatset2(titles, x, y);
			PointStyle[] styles;
			int[] colors ;
			
			if(lastweekValue.length()!=0){
				 colors = new int[] { Color.BLUE,Color.RED };// 每条曲线的颜色
				 styles = new PointStyle[] { PointStyle.CIRCLE,PointStyle.CIRCLE };
				
			}else{
				
				colors = new int[] { Color.BLUE};// 每条曲线的颜色
			    styles = new PointStyle[] { PointStyle.CIRCLE};
			
			}
		
			// 每条曲线点的形状
			
			// 曲线图的格式，包括颜色，值的范围，点和线的形状等等
			XYMultipleSeriesRenderer renderer = buildRenderer2(colors, styles,
					true);

			setChartSettings2(renderer, "城区交通指数柱状图", "(城区)", "交通指数", -5, 9, 0,
					10, Color.BLACK, Color.BLACK);

			View chart = ChartFactory.getBarChartView(this, dataset, renderer,
					Type.DEFAULT);

			// setContentView(chart);
			// setContentView(R.layout.main);
			LinearLayout layout = (LinearLayout) findViewById(R.id.histogram);
			layout.removeAllViews(); // 先remove再add可以实现统计图更新
			layout.addView(chart, new LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT));
		}

	}

	protected void setChartSettings2(XYMultipleSeriesRenderer renderer,
			String title, String xTitle, String yTitle, double xMin,
			double xMax, double yMin, double yMax, int axesColor,
			int labelsColor) {
		renderer.getSeriesRendererAt(0).setDisplayChartValues(true);
		renderer.getSeriesRendererAt(0).setChartValuesTextAlign(Align.CENTER);
		renderer.setBarSpacing(0.5f);
		renderer.setLegendTextSize(20);
		renderer.setChartTitle(title);
		renderer.setXTitle(xTitle);
		renderer.setAxisTitleTextSize(20);
		renderer.setChartTitleTextSize(20);
		renderer.setYTitle(yTitle);
		renderer.setXAxisMin(xMin);
		renderer.setMarginsColor(Color.parseColor("#a6d8ff"));
		renderer.setDisplayValues(true);

		renderer.setXAxisMax(xMax);
		renderer.setYAxisMin(yMin);
		renderer.setYAxisMax(yMax);

		renderer.setPanEnabled(false, false);// 设置Y轴不可拖动 X轴可以拖动
		renderer.setPanLimits(new double[] { 0, 50, 0, 1000 });// 设置拖动范围
																// X最小为0最大为50Y最小为0最大为1000
		renderer.setShowGrid(true);// 显示网格线
		renderer.setGridColor(Color.BLACK);

		// renderer.setApplyBackgroundColor(true);
		// renderer.setBackgroundColor(Color.GRAY);
		//renderer.setXLabelsAngle(-25); // 设置 X 轴标签倾斜角度 (clockwise degree)
		renderer.setDisplayChartValues(true);// 显示折线点上的数据
		renderer.setXLabels(0); // 设置X轴不显示数字（改用我们手动添加的文字标签）
		renderer.setAxesColor(axesColor);// 设置轴的颜色
		renderer.setXLabelsColor(labelsColor);// 设置X轴的字体颜色
		renderer.setYLabelsColor(0, Color.BLACK);// 设置Y轴的字体颜色
		renderer.setLabelsColor(labelsColor);
		renderer.setZoomEnabled(false, false);// 设置X轴可以缩放 Y轴不允许缩放
		renderer.setLabelsTextSize(20);
		for (int i = 0; i < xAxesString2.size(); i++) {
			
			renderer.addTextLabel(i, xAxesString2.get(i));

		}
		/*
		 * for(int i=0;i<25;i++){ if(i%4==0){
		 * 
		 * 
		 * }
		 * 
		 * }
		 */
	}

	private XYMultipleSeriesRenderer buildRenderer2(int[] colors,
			PointStyle[] styles, boolean fill) {
		// 曲线图的格式，包括颜色，值的范围，点和线的形状等等
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		int length = colors.length;
		for (int i = 0; i < length; i++) {
			XYSeriesRenderer r = new XYSeriesRenderer();
			r.setColor(colors[i]);
			r.setChartValuesTextSize(18);
			r.setChartValuesTextAlign(Align.CENTER);
			r.setPointStyle(styles[i]);
			r.setFillPoints(fill);
			renderer.addSeriesRenderer(r);
		}

		return renderer;
	}

	private XYMultipleSeriesDataset buildDatset2(String[] titles, List xValues,
			List yValues) {
		// 用于数据的存放
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();

		int length = titles.length; // 有几条线
		for (int i = 0; i < length; i++) {
			// XYseries对象,用于提供绘制的点集合的数据
			XYSeries series = new XYSeries(titles[i]); // 根据每条线的名称创建
			
			double[] xV = (double[]) xValues.get(i); // 获取第i条线的数据
			double[] yV = (double[]) yValues.get(i);
			int seriesLength = xV.length; // 有几个点

			for (int k = 0; k < seriesLength; k++) // 每条线里有几个点
			{
				series.add(xV[k], yV[k]);
			}

			dataset.addSeries(series);
		}

		return dataset;
	}
}
